﻿#region Copyright (C) 2012 Francisco Monteiro
/*

Morpheme
Copyright (C) 2012 Francisco Monteiro

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

http://code.google.com/p/morpheme-tumblr-theme/

*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TumblrAPI {
	public static class TumblrAPIv1 {
		public class TumblrBlog {
			public string Title { get; set; }
			public string Description { get; set; }
			public string Name { get; set; }
			public string Timezone { get; set; }
			public string CName { get; set; }
			//[] Feeds
		}

		public enum TumblrPostType {
			photo,
			answer,
			audio,
			video,
			link,
			quote,
			regular,
			conversation,

			none
		}

		public class TumblrPost {
			public string Id { get; set; }
			public string Url { get; set; }
			public string UrlWithSlug { get; set; }
			public TumblrPostType Type { get; set; }
			public string DateGMT { get; set; }
			public string Date { get; set; }
			public int Bookmarklet { get; set; }
			public int Mobile { get; set; }
			public string FeedItem { get; set; }
			public string FromFeedId { get; set; }
			public string UnixTimestamp { get; set; }
			public string Format { get; set; }
			public string ReblogKey { get; set; }
			public string Slug { get; set; }


			// <Photo Post>
			public string PhotoCaption { get; set; }
			public string PhotoLinkUrl { get; set; }
			public string PhotoUrl1280 { get; set; }
			public string PhotoUrl500 { get; set; }
			public string PhotoUrl400 { get; set; }
			public string PhotoUrl250 { get; set; }
			public string PhotoUrl100 { get; set; }
			public string PhotoUrl75 { get; set; }
			public int Width { get; set; }
			public int Height { get; set; }
			//[] Photos
			// </Photo Post>

		}


		public static void Read(
			string url,
			int start,
			int num,
			TumblrPostType type,

			out TumblrBlog blog_out,
			out TumblrPost[] posts_out
		) {
			read(
				url,
				start,
				num,
				type,
				null,
				null,

				out blog_out,
				out posts_out
			);
		}
		public static void Read(
			string url,
			string id,

			out TumblrBlog blog_out,
			out TumblrPost post_out
		) {
			TumblrPost[] posts;
			read(
				url,
				null,
				null,
				TumblrPostType.none,
				null,
				id,

				out blog_out,
				out posts
			);

			post_out = (
				(posts == null) ||
				(posts.Length <= 0)
			)
				? null
				: posts[0];
		}

		public static void Read(
			string url,
			string tag,

			out TumblrBlog blog_out,
			out TumblrPost[] posts_out
		) {
			read(
				url,
				null,
				null,
				TumblrPostType.none,
				tag,
				null,

				out blog_out,
				out posts_out
			);
		}

		private static void read(
			string url,
			int? start,
			int? num,
			TumblrPostType postType,
			string tag,
			string id,

			out TumblrBlog blog_out,
			out TumblrPost[] posts_out
		) {
			#region string jsonUrl = ...;
			string jsonUrl;
			if (!string.IsNullOrWhiteSpace(id)) {
				jsonUrl = string.Format(
					"{0}/api/read/json?id={1}",
					url,
					id
				);
			} else if (!string.IsNullOrWhiteSpace(tag)) {
				jsonUrl = string.Format(
					"{0}/api/read/json?num=50&tagged={1}",
					url,
					tag
				);
			} else {
				if (
					(start == null) ||
					(num == null)
				) {
					if (
						(start == null) &&
						(num == null)
					) {
						throw new ArgumentNullException("'start' and 'num' must be supplied");
					} else if (start == null) {
						throw new ArgumentNullException("'start' must be supplied");
					} else if (num == null) {
						throw new ArgumentNullException("'num' must be supplied");
					}
				}

				jsonUrl = string.Format(
					"{0}/api/read/json?start={1}&num={2}{3}",
					url,
					start.Value,
					num.Value,
					((postType == TumblrPostType.none)
						? ""
						: string.Format("&type={0}", postType.ToString())
					)
				);
			}
			#endregion
			string jsonString = utils.ReadURL_ToString(jsonUrl);

			jsonString = jsonString.Replace("var tumblr_api_read = ", "");
			jsonString = jsonString.Substring(0, jsonString.LastIndexOf(';'));

			// ToDos: here! need to find out how to work keys with minus on Newtonsoft.Json
			jsonString = jsonString.Replace("\"feed-item\":", "FeedItem:");
			jsonString = jsonString.Replace("\"from-feed-id\":", "FromFeedId:");
			jsonString = jsonString.Replace("\"reblog-key\":", "ReblogKey:");
			jsonString = jsonString.Replace("\"url-with-slug\":", "UrlWithSlug:");
			jsonString = jsonString.Replace("\"date-gmt\":", "DateGmt:");
			jsonString = jsonString.Replace("\"unix-timestamp\":", "UnixTimestamp:");
			//---
			jsonString = jsonString.Replace("\"photo-caption\":", "PhotoCaption:");
			jsonString = jsonString.Replace("\"photo-link-url\":", "PhotoLinkUrl:");
			jsonString = jsonString.Replace("\"photo-url-1280\":", "PhotoUrl1280:");
			jsonString = jsonString.Replace("\"photo-url-500\":", "PhotoUrl500:");
			jsonString = jsonString.Replace("\"photo-url-400\":", "PhotoUrl400:");
			jsonString = jsonString.Replace("\"photo-url-250\":", "PhotoUrl250:");
			jsonString = jsonString.Replace("\"photo-url-100\":", "PhotoUrl00:");
			jsonString = jsonString.Replace("\"photo-url-75\":", "PhotoUrl75:");

#if !DEBUG
			try {
#endif
			JObject json = JObject.Parse(jsonString);

			blog_out = JsonConvert.DeserializeObject<TumblrBlog>(json["tumblelog"].ToString());

			IList<JToken> results = json["posts"].Children().ToList();
			posts_out = new TumblrPost[results.Count];
			for (int i = 0; i < results.Count; i++) {
				posts_out[i] = JsonConvert.DeserializeObject<TumblrPost>(
					results[i].ToString()
				);
			}
#if !DEBUG
			} catch {
				// ToDos: here!
				blog_out = null;
				posts_out = null;
			}
#endif
		}
	}
}
